<?php

namespace app\index\model;

use think\DB;
use think\Model;


class Minimodel extends Model
{
  function getSwiper()
  {
    $data = db('goods')
      ->field('gid , g_longImg ')
      ->where(['g_state' => 0])
      ->order('g_end_money desc')
      ->limit(0, 5)
      ->select();

    return $data;
  }

  function getCategroy()
  {
    $res = db('classify')
      ->field('cid , c_name')
      ->where('fid != 0')
      ->select();

    // $classArr = [];
    foreach ($res as $key => &$value) {

      $item = db('goods')
        ->where("cid = {$value['cid']}")
        ->field('gid , g_longImg ,g_name ,g_start_money ,g_end_money , followers_num')
        ->where(['g_state' => 0])
        ->select();
      $value['children'] = $item;
    }
    return res(1000, 'ok', $res);
  }
  // getGoodsdetail
  function getGoodsDetail($gid){

    $sql ="SELECT g.gid,g.g_name , g.g_start_money , g.g_video , g.g_text , g.followers_num ,g.g_longImg , g.start_time ,g.keep_time,g.g_end_money,
    u.nickname , u.head
    FROM gjc_goods  g 
    left join gjc_user u on g.g_sponsor = u.uid
    
    WHERE gid = '{$gid}' ";
    $data =  DB::query($sql)[0];

    $sql = "SELECT imgsrc 
    FROM  gjc_childImg
    WHERE gid = {$gid} ";

    $childredImg =  DB::query($sql);
    
    $data['childImg'] = $childredImg ;

    return $data;
  }
  // 首页获取 最新上架 最热商品 即将结束  数据


  function homeGetGoods()
  { 
    $hot['name'] = '热门推荐';
    $hot['data'] = db('goods')
    ->field('g_name,g_start_money,g_picture,gid')
    ->order('followers_num desc')
    ->limit('0,4')
    ->select();


    $news['name'] = '最新上架';
    $news['data']= db('goods')
    ->field('g_name,g_start_money,g_picture,gid')
    ->order('g_create_time desc')
    ->limit('0,4')
    ->select();

    
    $end['name'] = '即将结束';
    $end['data']= db('goods')
    ->field('g_name,g_start_money,g_picture,gid')
    ->order('g_create_time asc')
    ->limit('0,4')
    ->select();


    return [$hot,$news,$end];


  }
  function getGoodsItem($gid){
    $data = db('goodsitem')
    ->alias('i')
    ->field('i.*,g.g_picture')
    ->join('gjc_goods g','i.gid = g.gid')
    ->where('i.gid',$gid)
    ->select();
    return $data;

  }
  function userLogin($openid)
  {
    // 先查询这个openid在数据库中是否注册过
    $user = db('user')
    ->where(['openid'=>$openid])
    ->find();
    // 如果没有注册过，那么注册一个账号
    if (!$user) {
      //账号随机生成一个
      $acc = 'wx'. time(). mt_rand(1,100000);
      $newU=[
        'acc'=>$acc,
        'nickname'=>$acc,
        'pwd'=>myMd5('abc123'),
        'create_time'=>date('yy-mm-dd H:i:s'),
        'money'=>1000000,
        'openid'=>$openid
      ];

      $res = db('user')->insert($newU);
      return $res;
    }

    return $user;

  }
  // 确认金钱是否足够
  function checkMoeny($openid,$money){
    $user = db('user')
    ->where(['openid'=>$openid])
    ->find();


    if ($user['money']<$money) {
      return false;
    }
    return [
      'uid'=>$user['uid'],
      'balance'=>$user['money']  -  $money
    ] ;
  }
  // 增加订单信息

  function insetOrder($data)
  {
    $inertData = [
      'uid'=>$data['uid'],
      'gid'=>$data['gid'],
      'g_item_id'=>$data['itemId'],
      'count'=>$data['count'],
      'time'=>date('Y-m-d H:i:s'),
      'state'=>2,
      'order_id'=>time().mt_rand(1000,9999) 
    ];
    $res=  db('order')->insert($inertData);

    return $res;


  }
  // 扣钱函数

  function demoney($data){
    $res = db('user')
    ->where(['uid'=>$data['uid']])
    ->update(['money'=>$data['balance']]);
    return $res === 1  ? true :  false ;

  }

  function getOrder($openid)
  {
    $res = db('user')
    ->field('i.`name`, i.price , g.g_picture , o.state , u2.head shop_head , u2.nickname shop_name, o.count , o.id' )
    ->alias('u')
    ->join('gjc_order o','o.uid = u.uid')
    ->join('gjc_goods g','o.gid = g.gid')
    ->join('gjc_user u2','u2.uid = g.g_sponsor')
    ->join('gjc_goodsitem i','o.g_item_id = i.id')
    ->where(['u.openid'=>$openid])
    ->order('o.time desc')
    ->select();

    return $res;

  }

  function updateOrder($oid,$state ){
    $res = db('order')->where(['id'=>$oid])->update(['state'=>$state]);
    if ($res === 1) {
      return true ;
    }
    return false;
  }

  function addHistory($oid,$gid ){
    // 先找到这个用户的用户id
    $uid = db('user')->where(['openid'=>$oid])->find()['uid'];
    if (!$uid) {
      return false;
    }

    
    $findRes = db('change')->where(['uid'=>$uid,'param1'=>$gid,'change_id'=>2002])->find();
    if (!$findRes) {
      # code...
      $data = [
        'uid'=>$uid,
        'param1'=>$gid,
        'time'=>time(),
        'change_id'=>2002
      ];
  
      return db('change')->insert($data);
    }else{
      return db('change')->where(['id'=>$findRes['id']])->update(['time'=>time()]);
    }

  }

  function collectGoods($oid,$gid , $is )
  { 
    // 获得用户id
    $uid = db('user')->where(['openid'=>$oid])->find()['uid'];
    if (!$uid) {
      return false;
    }
    $findRes = db('change')->where(['uid'=>$uid,'param1'=>$gid,'change_id'=>2000])->find();

    // 判断是收藏/取消收藏
    if ($is) {
      // 先找一下，是否曾经收藏过
      if (!$findRes) {
        // 如果没有收藏，增加一条数据
        $data = [
          'uid'=>$uid,
          'param1'=>$gid,
          'time'=>time(),
          'change_id'=>2000
        ];
    
        return db('change')->insert($data);
      }else{
        // 否则更新一下时间
        return db('change')->where(['id'=>$findRes['id']])->update(['time'=>time()]);
      }

      
    }

    // 如果不是则取消收藏 删除那条记录
    return db('change')->where(['id'=>$findRes['id']])->delete();


  }
  
  function getCollectGoods($oid)
  {
    // 先获得用户的信息
    $uid = db('user')->where(['openid'=>$oid])->find()['uid'];
    if (!$uid) {
      return false;
    }
    // 开始寻找用户关注的商品

    $collect = db('change')
    ->field('g.gid , g.g_longImg , g.g_name , g.g_start_money , g.g_end_money , g.followers_num')
    ->alias('c')
    ->join('gjc_goods g','c.param1 = g.gid')
    ->order('c.time desc')
    ->where([ 
      'c.uid'=>$uid,
      'change_id'=>2000
    ])
    ->select();

    $history = db('change')
    ->field('g.gid , g.g_longImg , g.g_name , g.g_start_money , g.g_end_money , g.followers_num')
    ->alias('c')
    ->join('gjc_goods g','c.param1 = g.gid')
    ->order('c.time desc')
    ->where([ 
      'c.uid'=>$uid,
      'change_id'=>2002
    ])
    ->select();
    return [$collect,$history];

  }
  function goodsQuery($key)
  {
    return db('goods')
    ->field('gid , g_longImg , g_name , g_start_money , g_end_money , followers_num')
    ->where("g_name like '%{$key}%' ")
    ->select();

  }

}

